package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.IOUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.service.common.file.FileBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.common.file.result.FileDownloadVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.common.file.vo.FileDownloadParam;
import com.cloudbroker.bcs.platform.dav.bizapi.service.common.file.vo.FileUploadParam;
import com.cloudbroker.bcs.platform.dav.common.extservice.store.StoreService;
import com.cloudbroker.bcs.platform.dav.common.extservice.store.StoreServiceFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhaojp18008 on 2016/5/11.
 */
@Service
public class FileBizServiceImpl  implements FileBizService {
    private static final Logger logger = LoggerFactory.getLogger(FileBizServiceImpl.class);
    @Override
    public HSBCPSBackVO uploadFile(FileUploadParam param) {
        try(InputStream ips = IOUtil.base64StringToStream(param.getFile())) {
            StoreService storeService = StoreServiceFactory.getInstance().getStoreService();
            storeService.uploadFile(param.getKey() , ips);
        } catch (Exception e) {
            logger.error("upload file error " , e);
        }
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public FileDownloadVo downloadFile(FileDownloadParam param) {
        FileDownloadVo fileDownloadVo = new FileDownloadVo();
        StoreService storeService = StoreServiceFactory.getInstance().getStoreService();
        try ( InputStream ips = storeService.downloadFile(param.getKey()) ) {
            fileDownloadVo.setFile(IOUtil.streamToBase64String(ips));
        } catch (IOException e) {
            logger.error("download file error " , e);
        }
        return VOUtil.setSuccessResult(fileDownloadVo);
    }
}
